package com.gitee.poi.plugin.core.advice;

import com.gitee.poi.plugin.annotations.core.AutoSizeColumn;
import com.gitee.poi.plugin.model.FieldStyle;
import com.gitee.poi.plugin.model.SheetInfo;
import org.apache.poi.ss.usermodel.Sheet;

import java.lang.reflect.Field;
import java.util.List;

/**
 * @author wangxin
 * 设置列的自动列宽
 * @time 2018/11/7 10:28
 */
public class AutoSizeColumnAdvice implements ExcelAdvice {
    @Override
    public SheetInfo beforeWrite(SheetInfo sheetInfo) {
        return sheetInfo;
    }

    @Override
    public SheetInfo afterWrite(SheetInfo sheetInfo) {
        Class clazz = sheetInfo.getClazz();
        List<FieldStyle> fields = sheetInfo.getFields();
        Sheet sheet = sheetInfo.getSheet();
        AutoSizeColumn autoSizeColumn = (AutoSizeColumn) clazz.getAnnotation(AutoSizeColumn.class);
        if(autoSizeColumn != null){
            boolean useMergedCells = autoSizeColumn.useMergedCells();
            for (int i = 0; i < fields.size(); i++) {
                sheet.autoSizeColumn(i,useMergedCells);
            }
        }else{
            for (int i = 0; i < fields.size(); i++) {
                FieldStyle fieldStyle =  fields.get(i);
                Field field = fieldStyle.getField();
                AutoSizeColumn fieldAutoSize = field.getAnnotation(AutoSizeColumn.class);
                if(fieldAutoSize != null){
                    boolean useMergedCells = fieldAutoSize.useMergedCells();
                    sheet.autoSizeColumn(i,useMergedCells);
                }
            }
        }
        return sheetInfo;
    }
}
